package com.zoe.sec03oauth2.dao;


import com.zoe.sec03oauth2.entity.Permission;
import com.zoe.sec03oauth2.entity.Role;
import com.zoe.sec03oauth2.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Zoe
 * @Date: 2021/03/30
 * @Description
 */
@Repository
public class UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据账号查询用户信息
    public User getUserByUsername(String username){
        String sql = "select id,username,password,fullname,mobile from t_user where username = ?";
        //连接数据库查询用户
        List<User> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(User.class));
        if(list !=null && list.size()==1){
            return list.get(0);
        }
        return null;
    }

    //根据用户id查询用户权限
    public List<String> findPermissionsByUserId(Long userId){
        String sql = "SELECT * FROM t_permission WHERE id IN(\n" +
            "\n" +
            "SELECT permission_id FROM t_role_permission WHERE role_id IN(\n" +
            "  SELECT role_id FROM t_user_role WHERE user_id = ? \n" +
            ")\n" +
            ")\n";

        String sql1 = "select a.* from t_permission a left join  t_role_permission b on a.id = b.permission_id left join t_user_role c on b.role_id = c.role_id where c.user_id = ?";
        List<Permission> list = jdbcTemplate.query(sql1, new Object[]{userId}, new BeanPropertyRowMapper<>(Permission.class));
        List<String> permissions = new ArrayList<>();
        list.forEach(c -> permissions.add(c.getCode()));
        return permissions;
    }
    //根据用户id查询用户权限
    public List<String> findRoleByUserId(Long userId){

        String sql1 = "select a.* from t_role a left join t_user_role b on a.id = b.role_id where b.user_id = ?";
        List<Role> list = jdbcTemplate.query(sql1, new Object[]{userId}, new BeanPropertyRowMapper<>(Role.class));
        List<String> roles = new ArrayList<>();
        list.forEach(c -> roles.add(c.getRoleName()));
        return roles;
    }


}
